// 添加流水账
const addJournal = (data) => {

	return new Promise(resolve => {

		let newObj = vk.pubfn.deepClone(data);
		newObj.amount = parseFloat(newObj.amount)

		newObj.cardid = '100' // 账户ID
		newObj.bookid = getApp().globalData.bookid // 账本ID
		newObj.year = vk.pubfn.timeFormat(newObj.datetime, "yyyy")
		newObj.month = vk.pubfn.timeFormat(newObj.datetime, "MM")
		newObj.day = vk.pubfn.timeFormat(newObj.datetime, "dd")

		if (!newObj.amount || newObj.bookid === "") {
			vk.toast('请选择账本');
			resolve(false)
			return
		}

		if (!newObj.amount || newObj.amount <= 0) {
			vk.toast('请输入金额');
			resolve(false)
			return
		}

		if (newObj.class_id == "") {
			vk.toast('请选择分类');
			resolve(false)
			return
		}

		vk.callFunction({
			url: 'client/book/book.UserJournalAdd',
			title: '请求中...',
			data: newObj,
			success: (res) => {
				if (res.id && res.id !== '') {
					newObj._id === "" ? vk.toast('添加成功') : vk.toast('修改成功');
					setTimeout(function() {
						vk.navigateBack();
						resolve(true)
					}, 2000)
				} else {
					vk.toast('添加失败');
					resolve(false)
				}
			},
			fail: () => {
				resolve(false)
			}
		});
	})
}



// 流水账列表
const listJournal = (year, month) => {
	return new Promise(resolve => {
		vk.callFunction({
			url: 'client/book/book.UserJournalList',
			data: {
				year,
				month,
				page: 1,
				bookid: getApp().globalData.bookid,
				pageSize: 2000
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: () => {
				resolve(false)
			}
		});
	})
}



// 添加账本
const addBook = (title, system) => {
	return new Promise(resolve => {
		vk.callFunction({
			url: 'client/book/book.BookAdd',
			data: {
				title,
				system,
			},
			success: (data) => {
				if (data.code === 0) {
					resolve(data.id)
				} else {
					resolve(0)
				}
			}
		});
	})
}



// 删除流水账
const deleteJournal = (id) => {
	return new Promise(resolve => {
		vk.callFunction({
			url: 'client/book/book.UserJournalDelete',
			title: '请求中...',
			data: {
				_id: id
			},
			success: (data) => {
				vk.toast("删除成功", "none", 1000, true, () => {
					vk.navigateBack();
				});
			}
		});
	})
}


// 修改用户默认账本
const updateUserDefaultBook = (bookid) => {
	return new Promise(resolve => {
		vk.callFunction({
			url: 'client/user/userbook.UpdateDefault',
			data: {
				bookid
			},
			success: (data) => {
				if (data.code === 0) {
					resolve(true)
				} else {
					resolve(false)
				}
			}
		});
	})
}






export {
	addJournal,
	listJournal,
	deleteJournal,
	addBook,
	updateUserDefaultBook,
}